<?php

namespace app\admin\middleware;


use think\facade\Cache;
use think\facade\Cookie;
use think\facade\View;

class LoginMiddleware extends BaseMiddleware
{
    public function handle($request, \Closure $next)
    {
        // 获取cookie中的token值
        $token = Cookie::get('token');

        if (empty(Cache::exists($token))) {
            if ($request->isGet()) {
                return redirect('/admin/login');
            } else {
                return $this->responseError('请先登录', -1);
            }
        } else {
            $account = Cache::get($token);
        }

        // 添加请求参数
        $request->account = $account;

        // 渲染用户数据
        View::assign('account', $account);
        return $next($request);
    }
}